<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\LoginRequest;
use App\Http\Requests\UserUpdateRequest;
use App\Http\Resources\UserResource;
use App\Services\OpenLoginService;
use Jiannei\Response\Laravel\Support\Facades\Response;

class UserController extends Controller
{
    public function login(LoginRequest $request, OpenLoginService $service)
    {
        $user = $service->getLoginUser($request->type, $request->all());
        if (empty($user)) {
            Response::fail('登录失败！');
        }

        $token = auth()->login($user);
        return Response::success($this->tokenArray($token));
    }

    public function me()
    {
        return Response::success(new UserResource(auth()->user()));
    }

    public function update(UserUpdateRequest $request)
    {
        $data = $request->only(['avatar', 'name', 'phone', 'email']);
        auth()->user()->update($data);

        return Response::ok();
    }

    public function logout()
    {
        auth()->logout();

        return Response::success([], 'Successfully logged out');
    }

    public function refresh()
    {
        return Response::success($this->tokenArray(auth()->refresh()));
    }

    protected function tokenArray($token)
    {
        $expireSeconds = auth()->factory()->getTTL() * 60;
        return [
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => $expireSeconds,
            'expired_at' => now()->addSeconds($expireSeconds)->toDateTimeString(),
        ];
    }
}
